package com.yesido.springcloud.controller;

import com.yesido.pojo.User;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yesido
 * @description http的测试类
 * @date 2023-06-05 0:02
 * @Version 8.3
 */
@RestController
@RequestMapping("httpTest")
public class HttpTest {
    private static final String REST_URL_PREFIX = "http://localhost:8101/";
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * http接口都能访问 我为啥需要eureka
     * @param id
     * @return
     */
    @GetMapping("getUserById/{id}")
    public User getUserById(@PathVariable("id") Integer id){

        String url = buildUrl(id);
//        User user = restTemplate.getForObject(REST_URL_PREFIX + "pd1/findUserById/" + id, User.class);
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    private String buildUrl(Integer id) {
        // 获取所有的注册服务信息
        List<String> services = discoveryClient.getServices();
        services.forEach(s -> System.out.println(s));
        for (String service : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            if (!CollectionUtils.isEmpty(instances)){
                ServiceInstance instance = instances.get(0);
                if (instance!=null){
                    return new StringBuilder("http://").append(instance.getHost()).append(":").append(instance.getPort()).append("/pd1/findUserById/").append(id).toString();
                }
            }
        }
        return "";
    }
}
